package com.example.admin.androidtest.threadpool;

import android.support.annotation.NonNull;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by admin on 2017/12/25.
 */

public class AppThreadManager {
    /**
     * 线程管理器实例，为单例模式
     */
    private static volatile AppThreadManager Instance = null;
    /**
     * 线程池，出于安全考虑，把他设为私有
     */
    private ExecutorService threadPool;

    private AppThreadManager() {
        if (threadPool == null) {
            /** 确保只存在一个线程池，这是一个无界线程池*/
            threadPool = Executors.newCachedThreadPool();
        }
    }

    /**
     * 获得线程管理器对象 <br>
     * 使用了double-check单例模式创建。
     *
     * @return
     */
    public static AppThreadManager get() {
        if (Instance == null) {
            synchronized (AppThreadManager.class) {
                if (Instance == null) {
                    Instance = new AppThreadManager();
                    return Instance;
                } else return Instance;
            }
        } else return Instance;
    }

    /**
     * 启动一个任务
     *
     * @param runnable
     */
    public void start(@NonNull Runnable runnable) {
        threadPool.execute(runnable);
    }

    /**
     * 使用submit（）方法启动线程
     *
     * @param task
     * @param <T>
     * @return
     */
    public <T> Future<T> submit(@NonNull Callable<T> task) {
        return threadPool.submit(task);
    }

    /**
     * 关闭线程池
     */
    public void stop() {
        if (Instance == null) {
            return;
        }
        synchronized (this) {
            if (Instance != null) {
                threadPool.shutdownNow();
            }
            Instance = null;
        }
    }

}
